package sing.flutter;

import android.app.Activity;
import android.net.Uri;
import android.widget.Toast;
import android.content.Intent;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baidu.idl.face.api.manager.FaceConst;
import com.baidu.idl.face.api.manager.FaceInitCallback;
import com.baidu.idl.face.api.manager.FaceServiceCallbck;
import com.baidu.idl.face.api.manager.FaceServiceManager;
import com.baidu.idl.face.platform.FaceEnvironment;
import com.baidu.idl.facelive.api.FaceLiveManager;
import com.baidu.idl.facelive.api.entity.FaceLiveConfig;
import com.baidu.idl.facelive.api.entity.FaceLivenessType;
import com.baidu.idl.facelive.api.entity.LivenessValueModel;
import com.baidu.ocr.sdk.OCR;
import com.baidu.ocr.sdk.OnResultListener;
import com.baidu.ocr.sdk.exception.OCRError;
import com.baidu.ocr.sdk.model.AccessToken;
import com.baidu.ocr.ui.camera.CameraNativeHelper;
import com.baidu.ocr.ui.camera.CameraView;
import com.bytedance.sdk.openadsdk.CSJSplashAd;
import com.umeng.commonsdk.UMConfigure;
import com.umeng.commonsdk.listener.OnGetOaidListener;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import sing.core.callback.Callback;
import sing.myapp.common.baidu.exception.FaceException;
import sing.myapp.common.baidu.model.LivenessVsIdcardResult;
import io.flutter.Log;
import io.flutter.embedding.android.FlutterActivity;
import io.flutter.embedding.engine.FlutterEngine;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import sing.core.util.AppUtil;
import sing.core.util.DeviceUtil;
import sing.core.util.MMkvUtil;
import sing.myapp.common.baidu.manager.ConsoleConfigManager;
import sing.myapp.common.baidu.model.Config;
import sing.myapp.common.baidu.model.ConsoleConfig;
import sing.myapp.common.baidu.utils.PoliceCheckResultParser;
import sing.myapp.router.JumpCenter;

public class FlutterPlugin implements MethodChannel.MethodCallHandler {
    public static final String CHANNEL = "sing.top/rth";
    static MethodChannel channel;
    public static FlutterEngine engine;
    public static CSJSplashAd ad;
    private Activity activity;
    private FlutterPlugin(Activity activity) {
        this.activity = activity;
    }
    public static FlutterPlugin registerWith(FlutterEngine flutterEngine, FlutterActivity activity) {
        channel = new MethodChannel(flutterEngine.getDartExecutor(), CHANNEL);
        FlutterPlugin instance = new FlutterPlugin(activity);
        //setMethodCallHandler在此通道上接收方法调用的回调
        channel.setMethodCallHandler(instance);
        //Toast.makeText(activity,"注册成功",Toast.LENGTH_SHORT).show();
        engine = flutterEngine;
        return instance;
    }

    @Override
    public void onMethodCall(MethodCall call, MethodChannel.Result result) {
        if(call.method.equals("getOaid")) {
            UMConfigure.getOaid(activity, s -> {
                if (s != null && !s.isEmpty()) { // 模拟器可能为空
                    result.success(s);
                    MMkvUtil mkvUtil = new MMkvUtil();
                    mkvUtil.setOaid(s);
                }else{
                    result.success("");
                }
            });
        } else if(call.method.equals("getImei")) {
            String imei = DeviceUtil.INSTANCE.getImei(activity);
            result.success(imei);
            MMkvUtil mkvUtil = new MMkvUtil();
            mkvUtil.setImei(imei);
//            channel.invokeMethod("getToken", s);
        } else if(call.method.equals("setData")) {
            int channel_id = call.argument("channel_id");
            String token = call.argument("token");
            String phone = call.argument("phone");
            Log.e("11111111","token = " + token);
            MMkvUtil mkvUtil = new MMkvUtil();
            mkvUtil.setToken(token);
            mkvUtil.setUserPhone(phone);
            mkvUtil.setChannelId(channel_id);
        } else if(call.method.equals("getNetParams")) {
            boolean isTestUrl = call.argument("is_test_url");
            MMkvUtil mkvUtil = new MMkvUtil();
            mkvUtil.setTestUrl(isTestUrl);

            StringBuilder sb = new StringBuilder();
            sb.append("?os=2");
            sb.append("&network=" + new MMkvUtil().getNetwork());
            sb.append("&model=" + AppUtil.INSTANCE.getDeviceBrand());
            sb.append("&version=" + AppUtil.INSTANCE.getVersionName());
            String imei = mkvUtil.getImei();
            if (!imei.isEmpty()){
                sb.append("&device_id="+imei);
            }else{
                String oaid = mkvUtil.getOaid();
                sb.append("&device_id="+oaid);
            }
            sb.append("&device=Android");
            result.success(sb.toString());
        } else if(call.method.equals("toWebView")) {
            String url = call.argument("url");
            String title = call.argument("title");
            JumpCenter.INSTANCE.toWebView(url,title);
        } else if(call.method.equals("toCall")) {
            Intent intent = new Intent();
            intent.setAction(Intent.ACTION_DIAL);
            intent.setData(Uri.parse("tel:028-38289396"));
            activity.startActivity(intent);
        } else if(call.method.equals("toCalc")) {
            JumpCenter.INSTANCE.toCalc();
        } else if(call.method.equals("toFace")) {
            String name = call.argument("name");
            String identityNum = call.argument("identityNum");
            toFace(name,identityNum);
        } else if(call.method.equals("loadAd")) {
            if (callback != null){
                callback.result(200);
            }
        } else if(call.method.equals("initOCR")) { // 初始化OCR
            initOcr();
        } else if(call.method.equals("releaseOCR")) { // 释放OCR
            CameraNativeHelper.release();
        } else if(call.method.equals("scanIdCard")) { // 识别身份证
            boolean isFront = call.argument("is_front");
            if (idCardCallback != null){
                idCardCallback.result(isFront);
            }
        } else {
            Map<String,Object> map = new HashMap<String,Object>();
            map.put("222","222");
            result.success(map);
            Log.e("1111","android 打印："+"1111111");
        }
    }


    private void toFace(String name,String identityNum) {
        ConsoleConfig consoleConfig = ConsoleConfigManager.getInstance(activity.getApplication()).getConfig();
        FaceServiceManager.getInstance().init(activity, Config.licenseID, Config.licenseFileName, Config.keyName, new FaceInitCallback() {
            @Override
            public void onCallback(int i, String s) {
                //            "resultCode:${resultCode},resultMsg:${resultMsg}".showShort()

            }
        });
        // OCR初始化（初始化OCR SDK 使用的license是aip.license，名字不能修改）
        OCR.getInstance(activity).initAccessToken(new OnResultListener<AccessToken>() {
            @Override
            public void onResult(AccessToken result) {
                if (!result.getAccessToken().isEmpty()) {
                    Log.e("1111","ocr init success! accessToken = "+result.getAccessToken());
                    startFaceRecognize(result.getAccessToken(),name,identityNum);
                }
            }

            @Override
            public void onError(OCRError error) {
                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        String msg = "resultCode:"+error.getErrorCode()+",resultMsg:"+error.getMessage();
                        Toast.makeText(activity, msg, Toast.LENGTH_SHORT).show();
                    }
                });
            }
        }, activity.getApplicationContext());
    }

    private String recogType = FaceConst.FACE_RECOGNIZE;
    private void startFaceRecognize(String accessToken,String name,String identityNum) {
        setFaceQualityConfig(); // 人脸阈值设置
        Map<String, Object> params = new HashMap<>();
        // 必须携带access_token
        params.put("access_token", accessToken);
        // 开放平台控制台配置的方案Id
        params.put("plan_id",consoleConfig.getPlanId());

        if (FaceConst.FACE_RECOGNIZE.equals(recogType)) {
            // 身份证类型，0：大陆 1：港澳 2：外国 3：定居国外中国护照
            params.put("verify_type",0);
            // recogType为FaceRecognize 需要带姓名、证件号
            params.put("name",name);
            params.put("id_card_number",identityNum);

            params.put("quality_control",consoleConfig.getOnlineImageQuality());
            params.put("liveness_control",consoleConfig.getOnlineLivenessQuality());
        }

        FaceServiceManager.getInstance().startFaceRecognize(activity, params, new FaceServiceCallbck() {
            @Override
            public void onCallback(int resultCode, Map<String, Object> map) {
                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        handleResult(resultCode, map);
                    }
                });
            }
        });
    }

    private void handleResult(int resultCode,Map<String, Object> resultMap ) {
        if (consoleConfig == null){
            return;
        }
        if (resultCode == 0) {
            String data =  resultMap.get(FaceConst.RESULT_JSON).toString();
            PoliceCheckResultParser parser =  new PoliceCheckResultParser();
            try {
                LivenessVsIdcardResult result = parser.parse(data);

                if (result.getRiskLevel() == 1 || result.getRiskLevel() == 2) {
                    toFlutterFaceError(0,0,result.getRiskLevel());
                    return;
                }

                boolean isPass;
                if (FaceConst.FACE_LIVENESS == recogType) { // 在线活体方案：活体分数
                    isPass = result.getFaceliveness() >= 0.8;
                } else { // 实名认证方案：匹配度
                    isPass = result.getScore() >= consoleConfig.getRiskScore();
                }

                if (isPass) {
                    toFlutterFaceOk(result);
                } else { // 低分
                    toFlutterFaceError(FaceException.ErrorCode.LOW_SCORE, result.getVerifyStatus(), result.getRiskLevel());
                }
            } catch (FaceException e) { // 服务端错误
                toFlutterFaceError(e.getErrorCode(),0,0);
                e.printStackTrace();
            }
        } else { // SDK本地错误码
            Toast.makeText(activity, "resultCode : "+resultMap.get("resultMsg"), Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * console识别配置
     */
    private ConsoleConfig consoleConfig = null;
    private void setFaceQualityConfig() {
        consoleConfig = ConsoleConfigManager.getInstance(activity).getConfig();
        try {
            FaceLiveConfig faceLiveConfig = new FaceLiveConfig();
            // faceUI默认展示结果页，此处必须设置为false
            faceLiveConfig.setShowResultView(false);
            // 设置模糊度阈值
            faceLiveConfig.setBlurnessValue(consoleConfig.getBlur());
            // 设置最小光照阈值（范围0-255）
            faceLiveConfig.setBrightnessValue(consoleConfig.getIllumination());
            // 设置最大光照阈值（范围0-255）
            faceLiveConfig.setBrightnessMaxValue(consoleConfig.getMaxIllumination());
            // 设置左眼遮挡阈值
            faceLiveConfig.setOcclusionLeftEyeValue(consoleConfig.getLeftEyeOcclu());
            // 设置右眼遮挡阈值
            faceLiveConfig.setOcclusionRightEyeValue(consoleConfig.getRightEyeOcclu());
            // 设置鼻子遮挡阈值
            faceLiveConfig.setOcclusionNoseValue(consoleConfig.getNoseOcclu());
            // 设置嘴巴遮挡阈值
            faceLiveConfig.setOcclusionMouthValue(consoleConfig.getMouthOcclu());
            // 设置左脸颊遮挡阈值
            faceLiveConfig.setOcclusionLeftContourValue(consoleConfig.getLeftCheekOcclu());
            // 设置右脸颊遮挡阈值
            faceLiveConfig.setOcclusionRightContourValue(consoleConfig.getRightCheekOcclu());
            // 设置下巴遮挡阈值
            faceLiveConfig.setOcclusionChinValue(consoleConfig.getChinOcclu());
            // 设置人脸姿态Pitch阈值
            faceLiveConfig.setHeadPitchValue(consoleConfig.getPitch());
            // 设置人脸姿态Yaw阈值
            faceLiveConfig.setHeadYawValue(consoleConfig.getYaw());
            // 设置人脸姿态Roll阈值
            faceLiveConfig.setHeadRollValue(consoleConfig.getRoll());
            // 是否开启录制视频
            faceLiveConfig.setOpenRecord(false);
            // 设置是否显示超时弹框
            faceLiveConfig.setIsShowTimeoutDialog(true);
            // 输出图片类型：0原图、1抠图
            faceLiveConfig.setOutputImageType(FaceEnvironment.VALUE_OUTPUT_IMAGE_TYPE);
            // 是否忽略录制异常（只能忽略采集时间过短，采集后无文件输出的异常）
            faceLiveConfig.setIgnoreRecordError(true);
            // 眨眼张嘴遮挡开关
            faceLiveConfig.setActiveStrict(true);
            // 设置活体类型相关
            setFaceLivenessConfig(faceLiveConfig);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void setFaceLivenessConfig(FaceLiveConfig faceLiveConfig) {
        if (consoleConfig == null){
            return;
        }
        try {
            // 设置活体类型：炫彩活体、动作活体、静默活体
            FaceLivenessType faceLivenessType = null;
            // 配置活体动作集合、动作个数，活体阈值，无活体
            LivenessValueModel livenessValueModel = null;
            if (consoleConfig.getFaceLiveType() == 0) {
                faceLivenessType = FaceLivenessType.COLORLIVENESS;
                // 是否开启炫彩活体能力
                faceLiveConfig.setIsOpenColorLive(true);
                // 是否开启动作活体能力
                faceLiveConfig.setIsOpenActionLive(true);
                livenessValueModel = faceLiveConfig.getLivenessValueModel();
                livenessValueModel.actionList.addAll(consoleConfig.getActions());
                livenessValueModel.livenessScore = consoleConfig.getLiveScore();
            } else if (consoleConfig.getFaceLiveType() == 1) {
                faceLivenessType = FaceLivenessType.ACTIONLIVENESS;
                // 是否开启炫彩活体能力
                faceLiveConfig.setIsOpenColorLive(false);
                // 是否开启动作活体能力
                faceLiveConfig.setIsOpenActionLive(true);
                livenessValueModel = faceLiveConfig.getLivenessValueModel();
                livenessValueModel.actionList.addAll(consoleConfig.getActions());
                livenessValueModel.actionRandomNumber = consoleConfig.getFaceActionNum();
                livenessValueModel.livenessScore = consoleConfig.getLiveScore();
            } else if (consoleConfig.getFaceLiveType() == 2) {
                faceLivenessType = FaceLivenessType.SILENTLIVENESS;
                // 是否开启炫彩活体能力
                faceLiveConfig.setIsOpenColorLive(false);
                // 是否开启动作活体能力
                faceLiveConfig.setIsOpenActionLive(false);
                livenessValueModel = faceLiveConfig.getLivenessValueModel();
                livenessValueModel.livenessScore = consoleConfig.getLiveScore();
            } else if (consoleConfig.getFaceLiveType() == 3) {
                // 是否开启炫彩活体能力
                faceLiveConfig.setIsOpenColorLive(true);
                // 是否开启动作活体能力
                faceLiveConfig.setIsOpenActionLive(false);
                livenessValueModel = faceLiveConfig.getLivenessValueModel();
            }
            faceLiveConfig.setLivenessValueModel(livenessValueModel);
            FaceLiveManager.getInstance().setFaceConfig(faceLiveConfig);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 人脸识别成功 //////////////////////////////////////////////////////////////////////////////////////////////////
    private void toFlutterFaceOk(LivenessVsIdcardResult faceInfo){
        // riskLevel = 3, faceliveness = 0.0, score = 96.5, verifyStatus = 0, idcardImage = null, jsonRes = {"risk_level":"3","risk_tag":[],"dec_image":"/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/2wBDAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/wAARCAKAAeADASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8Q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fX1Vr99OaoEVZHRWIVm/5Zrg8YAK8AhSR2wCAfcVXNu6eayMwZyw8wHaQBwME4GVyeWAGect1OlEhjZZFVZHPy4O51ZFwCxHQH5SwzyAoI4G4xXAkln28R
        JSONObject obj = JSON.parseObject(faceInfo.getJsonRes());
        if (obj.containsKey("dec_image")){
            Map<String,String> map = new HashMap();
            map.put("dec_image", (String) obj.get("dec_image"));
            map.put("score",faceInfo.getScore()+"");
            toFlutter("faceOk",map);
        }
    }

    private void toFlutterFaceError(int errCode, int verifyStatus, int riskLevel){
        Map<String,Integer> map = new HashMap();
        map.put("err_code", errCode);
        map.put("verify_status",verifyStatus);
        map.put("risk_level",riskLevel);
        toFlutter("faceError",map);
    }

    public static void toFlutter(String method,Object arguments){
        channel.invokeMethod(method, arguments, new MethodChannel.Result() {
            @Override
            public void success(@Nullable Object result) {
            }

            @Override
            public void error(@NonNull String errorCode, @Nullable String errorMessage, @Nullable Object errorDetails) {
                Log.e("1111","android 打印："+errorMessage);

            }

            @Override
            public void notImplemented() {
                Log.e("1111","android 打印："+"notImplemented");

            }
        });
    }

    private Callback callback = null;
    public void setCallback(Callback callback) {
        this.callback = callback;
    }

    // 身份证 ////////////////////////////////////////////////////////////////////////////////////////////////
    private Callback idCardCallback = null;
    public void setIdCardCallback(Callback callback) {
        this.idCardCallback = callback;
    }
    private void initOcr() {
        OCR.getInstance(activity).initAccessToken(new OnResultListener<AccessToken>() {
            @Override
            public void onResult(AccessToken accessToken) {
                activity.runOnUiThread(() -> toFlutter("initOcrOk",""));

                new Thread(() -> {
                    try {
                        Thread.sleep(500);
                        CameraNativeHelper.init(activity, OCR.getInstance(activity).getLicense(), new CameraNativeHelper.CameraNativeInitCallback() {
                            @Override
                            public void onError(int errorCode, Throwable throwable) {
                                Map<String,String> map = new HashMap();
                                switch (errorCode){
                                    case CameraView.NATIVE_SOLOAD_FAIL:
                                        map.put("msg", "加载so失败，请确保apk中存在ui部分的so");
                                        break;
                                    case CameraView.NATIVE_AUTH_FAIL:
                                        map.put("msg", "授权本地质量控制token获取失败");
                                        break;
                                    case CameraView.NATIVE_INIT_FAIL:
                                        map.put("msg", "本地质量控制");
                                        break;
                                    default:
                                        map.put("msg", errorCode+"");
                                        break;
                                }
                                activity.runOnUiThread(() -> toFlutter("initOcrError",map));
                            }
                        });
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }).start();
            }

            @Override
            public void onError(OCRError ocrError) {
                Map<String,String> map = new HashMap();
                map.put("msg", ocrError.getMessage());
                activity.runOnUiThread(() -> toFlutter("initOcrError",map));
            }
        },activity);
    }

}